from rest_framework import serializers
from .models import (
    PersonalInfo,  # 个人信息主表
    WorkExperience,  # 工作/实习经历表
    ProjectExperience,  # 项目经历表
    EducationExperience  # 教育经历表
)


# ------------------------------
# 子序列化器：关联表数据处理
# ------------------------------

class WorkExperienceSerializer(serializers.ModelSerializer):
    """工作/实习经历子序列化器"""

    class Meta:
        model = WorkExperience
        # 包含所有字段（id为数据库自动生成，设为只读）
        fields = ['id', 'company', 'position', 'start_date', 'end_date', 'description']
        read_only_fields = ['id']  # 防止前端手动修改id

    # 可选：添加字段级验证（根据实际业务需求调整）
    def validate_company(self, value):
        """验证公司名称不为空且长度合理"""
        if value is None:
            raise serializers.ValidationError("公司名称不能为空")
        if not isinstance(value, str) or not value.strip():
            raise serializers.ValidationError("公司名称不能为空")
        if len(value) > 100:
            raise serializers.ValidationError("公司名称长度不能超过100个字符")
        return value

    def validate_start_date(self, value):
        """验证开始日期格式正确（数据库已限制为date类型，此处补充业务验证）"""
        from datetime import date
        if value > date.today():
            raise serializers.ValidationError("开始日期不能晚于当前日期")
        return value

    def validate_end_date(self, value):
        """验证结束日期不早于开始日期（若填写）"""
        # 安全获取初始数据：在嵌套序列化器中initial_data可能不存在
        if hasattr(self, 'initial_data') and self.initial_data:
            start_date = self.initial_data.get('start_date')
            if value and start_date and value < start_date:
                raise serializers.ValidationError("结束日期不能早于开始日期")
        return value

    def validate(self, attrs):
        """对象级别验证：确保结束日期不早于开始日期"""
        start_date = attrs.get('start_date')
        end_date = attrs.get('end_date')
        if start_date and end_date and end_date < start_date:
            raise serializers.ValidationError({
                'end_date': '结束日期不能早于开始日期'
            })
        return attrs


class ProjectExperienceSerializer(serializers.ModelSerializer):
    """项目经历子序列化器"""

    class Meta:
        model = ProjectExperience
        fields = ['id', 'project_name', 'role', 'start_date', 'end_date', 'description']
        read_only_fields = ['id']

    # 字段级验证
    def validate_project_name(self, value):
        if value is None:
            raise serializers.ValidationError("项目名称不能为空")
        if not isinstance(value, str) or not value.strip():
            raise serializers.ValidationError("项目名称不能为空")
        if len(value) > 100:
            raise serializers.ValidationError("项目名称长度不能超过100个字符")
        return value

    def validate_start_date(self, value):
        from datetime import date
        if value > date.today():
            raise serializers.ValidationError("开始日期不能晚于当前日期")
        return value

    def validate_end_date(self, value):
        # 安全获取初始数据：在嵌套序列化器中initial_data可能不存在
        if hasattr(self, 'initial_data') and self.initial_data:
            start_date = self.initial_data.get('start_date')
            if value and start_date and value < start_date:
                raise serializers.ValidationError("结束日期不能早于开始日期")
        return value

    def validate(self, attrs):
        """对象级别验证：确保结束日期不早于开始日期"""
        start_date = attrs.get('start_date')
        end_date = attrs.get('end_date')
        if start_date and end_date and end_date < start_date:
            raise serializers.ValidationError({
                'end_date': '结束日期不能早于开始日期'
            })
        return attrs


class EducationExperienceSerializer(serializers.ModelSerializer):
    """教育经历子序列化器"""

    class Meta:
        model = EducationExperience
        fields = ['id', 'school', 'education', 'major', 'start_date', 'end_date', 'description']
        read_only_fields = ['id']

    # 字段级验证
    def validate_school(self, value):
        if value is None:
            raise serializers.ValidationError("学校名称不能为空")
        if not isinstance(value, str) or not value.strip():
            raise serializers.ValidationError("学校名称不能为空")
        if len(value) > 100:
            raise serializers.ValidationError("学校名称长度不能超过100个字符")
        return value

    def validate_education(self, value):
        """验证学历为合法选项"""
        valid_educations = ['大专', '本科', '硕士', '博士']
        if value not in valid_educations:
            raise serializers.ValidationError(f"学历必须是以下选项之一：{', '.join(valid_educations)}")
        return value

    def validate_start_date(self, value):
        from datetime import date
        if value > date.today():
            raise serializers.ValidationError("入学日期不能晚于当前日期")
        return value

    def validate_end_date(self, value):
        # 安全获取初始数据：在嵌套序列化器中initial_data可能不存在
        if hasattr(self, 'initial_data') and self.initial_data:
            start_date = self.initial_data.get('start_date')
            if value and start_date and value < start_date:
                raise serializers.ValidationError("毕业日期不能早于入学日期")
        return value

    def validate(self, attrs):
        """对象级别验证：确保毕业日期不早于入学日期"""
        start_date = attrs.get('start_date')
        end_date = attrs.get('end_date')
        if start_date and end_date and end_date < start_date:
            raise serializers.ValidationError({
                'end_date': '毕业日期不能早于入学日期'
            })
        return attrs


# ------------------------------
# 主序列化器：个人信息+关联经历整合
# ------------------------------

class PersonalInfoSerializer(serializers.ModelSerializer):
    """个人信息主序列化器（包含所有关联经历）"""
    # 嵌套子序列化器：支持批量提交多条关联数据
    work_experiences = WorkExperienceSerializer(many=True, required=False, allow_empty=True)
    project_experiences = ProjectExperienceSerializer(many=True, required=False, allow_empty=True)
    education_experiences = EducationExperienceSerializer(many=True, required=False, allow_empty=True)

    class Meta:
        model = PersonalInfo
        # 主表所有字段 + 嵌套的关联字段
        fields = [
            'id', 'name', 'graduate_year', 'education', 'job_status',
            'phone', 'resume_score', 'optimization_items', 'preponderance',
            'expectedJob', 'work_experiences', 'project_experiences', 'education_experiences'
        ]
        read_only_fields = ['id']  # id由数据库自动生成，前端无需传递

    # ------------------------------
    # 验证逻辑（主表字段）
    # ------------------------------
    def validate_name(self, value):
        """验证姓名不为空且长度合理"""
        if value is None:
            raise serializers.ValidationError("姓名不能为空")
        if not isinstance(value, str) or not value.strip():
            raise serializers.ValidationError("姓名不能为空")
        if len(value) > 50:
            raise serializers.ValidationError("姓名长度不能超过50个字符")
        return value.strip()

    def validate_graduate_year(self, value):
        """验证应届年份格式（支持"2025届""24届""2026年应届生"等格式）"""
        if value is None:
            raise serializers.ValidationError("应届年份不能为空")
        if not isinstance(value, str) or not value.strip():
            raise serializers.ValidationError("应届年份不能为空")
        # 简单格式校验：包含数字（年份）和"届/年"关键字
        import re
        if not re.search(r'\d+', value) or not re.search(r'届|年', value):
            raise serializers.ValidationError("应届年份格式不正确（示例：2025届、24届、2026年应届生）")
        if len(value) > 20:
            raise serializers.ValidationError("应届年份长度不能超过20个字符")
        return value.strip()

    def validate_education(self, value):
        """验证学历为合法选项"""
        valid_educations = ['大专', '本科', '硕士', '博士', '其他']
        if value not in valid_educations:
            raise serializers.ValidationError(f"学历必须是以下选项之一：{', '.join(valid_educations)}")
        return value

    def validate_phone(self, value):
        """验证手机号格式（11位数字）"""
        if value is None:
            raise serializers.ValidationError("手机号不能为空")
        import re
        if not isinstance(value, str) or not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式不正确（必须是11位有效手机号）")
        return value

    def validate_resume_score(self, value):
        """验证简历评分在0-100之间"""
        if not (0 <= value <= 100):
            raise serializers.ValidationError("简历评分必须在0-100之间")
        return value

    def validate_optimization_items(self, value):
        """验证待优化项数量为非负整数"""
        if value < 0:
            raise serializers.ValidationError("待优化项数量不能为负数")
        return value

    def validate_expectedJob(self, value):
        """验证期望职位不为空"""
        if value is None:
            raise serializers.ValidationError("期望职位不能为空")
        if not isinstance(value, str) or not value.strip():
            raise serializers.ValidationError("期望职位不能为空")
        if len(value) > 100:
            raise serializers.ValidationError("期望职位长度不能超过100个字符")
        return value.strip()

    # ------------------------------
    # 业务逻辑（创建/更新）
    # ------------------------------
    def create(self, validated_data):
        """
        重写创建逻辑：先创建个人信息主表，再批量创建关联经历
        :param validated_data: 验证通过后的所有数据（含主表字段和关联字段）
        :return: 创建后的PersonalInfo实例
        """
        # 1. 从验证数据中提取关联经历数据（若前端未提交则设为空列表）
        work_exps_data = validated_data.pop('work_experiences', [])
        project_exps_data = validated_data.pop('project_experiences', [])
        edu_exps_data = validated_data.pop('education_experiences', [])

        # 2. 创建个人信息主表记录
        personal_info = PersonalInfo.objects.create(**validated_data)

        # 3. 批量创建关联经历（绑定到当前个人信息）
        # 工作经历
        for work_data in work_exps_data:
            WorkExperience.objects.create(personal_info=personal_info, **work_data)
        # 项目经历
        for project_data in project_exps_data:
            ProjectExperience.objects.create(personal_info=personal_info, **project_data)
        # 教育经历
        for edu_data in edu_exps_data:
            EducationExperience.objects.create(personal_info=personal_info, **edu_data)

        return personal_info

    def update(self, instance, validated_data):
        """
        重写更新逻辑：支持主表字段更新 + 关联经历的新增/修改/删除
        :param instance: 要更新的PersonalInfo实例（原数据）
        :param validated_data: 验证通过后的更新数据（含主表字段和关联字段）
        :return: 更新后的PersonalInfo实例
        """
        # 1. 提取关联经历数据（若前端未提交，则不处理该类经历）
        work_exps_data = validated_data.pop('work_experiences', None)
        project_exps_data = validated_data.pop('project_experiences', None)
        edu_exps_data = validated_data.pop('education_experiences', None)

        # 2. 更新个人信息主表字段（只更新前端提交的字段，未提交的保持原样）
        for attr, value in validated_data.items():
            # 确保属性存在且可设置
            if hasattr(instance, attr):
                setattr(instance, attr, value)
        instance.save()  # 保存主表更新

        # 3. 处理工作经历更新：删除原有记录，批量创建新记录（支持新增/编辑/删除）
        if work_exps_data is not None:
            # 安全删除：确保关联关系存在
            if hasattr(instance, 'work_experiences'):
                instance.work_experiences.all().delete()
            # 批量创建新记录
            for work_data in work_exps_data:
                WorkExperience.objects.create(personal_info=instance, **work_data)

        # 4. 处理项目经历更新（逻辑同上）
        if project_exps_data is not None:
            if hasattr(instance, 'project_experiences'):
                instance.project_experiences.all().delete()
            for project_data in project_exps_data:
                ProjectExperience.objects.create(personal_info=instance, **project_data)

        # 5. 处理教育经历更新（逻辑同上）
        if edu_exps_data is not None:
            if hasattr(instance, 'education_experiences'):
                instance.education_experiences.all().delete()
            for edu_data in edu_exps_data:
                EducationExperience.objects.create(personal_info=instance, **edu_data)

        return instance